<?php

namespace app\middleware;

use app\common\Send;
use app\utils\Jwt;
use think\facade\Cache;
use think\Request;
use app\exception\TokenException;
class ApiVerifyMiddleware
{
    use Send;
    /**
     * 处理请求
     *
     * @param \think\Request $request
     * @param \Closure       $next
     * @return Response
     */
    public function handle(Request $request, \Closure $next)
    {
        //验证请求路由是否包含 login或register 如果包含不做验证
        $path = $request->url();

        // 放行特定路径
        if (strpos($path, 'login') !== false || strpos($path, 'register') !== false) {
            return $next($request);
        }

        $authorization = $request->header("Authorization");
        //指定文件缓存驱动
        if(empty($authorization) || !Cache::store('file')->has($authorization))  throw new TokenException("请先登录");
        $user =Jwt::decodeToken($authorization,env('jwt.admin_secret',''));

        $request->_uid = $user->sub ?? 0;
        $request->_token = $authorization ?? '';

        return $next($request);
    }
}
